package com.zxl.permission.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import com.zxl.permission.dao.FeatureDao;
import com.zxl.permission.dao.GroupDao;
import com.zxl.permission.entity.Feature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.List;


@Service
@Transactional
public class FeatureService {
    @Autowired
    private FeatureDao featureDao;

    @Autowired
    private GroupDao groupDao;

    private JSONArray cacheData;

    public FeatureService() {
        try {
            StringBuilder buffer = new StringBuilder();
            File jsonFile = ResourceUtils.getFile("classpath:static/menu.json");
            InputStream is = new FileInputStream(jsonFile);
            String line;
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            line = reader.readLine();
            while (line != null) {
                buffer.append(line);
                line = reader.readLine();
            }
            reader.close();
            is.close();

            String json = buffer.toString();
            cacheData = JSON.parseArray(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


//    public JSONObject getMenuList(String username) {
//        // 组装返回包
//        JSONObject res = new JSONObject();
//        res.put("code", 0);//        res.put("msg", "success");
//        res.put("data", cacheData);
//        return res;
//    }

    public JSONObject getMenuList(String username) {
        // 拉取菜单列表
        List<Feature> rootFeatureList = featureDao.getFeatureListFromFatherId(0);
        for (Feature feature : rootFeatureList) {
            feature.childFeature = featureDao.getFeatureListFromFatherId(feature.id);
        }

        // 拉取用户拥有的视图编号列表
        List<Integer> permissionList = groupDao.getPermissionListFromUsername(username);
        System.out.println(permissionList);
        for (Feature feature : rootFeatureList) {
            feature.disable = false;
            for (Feature children : feature.childFeature) {
                children.disable = false;
                if (permissionList.contains(children.id)) {
                    children.disable = false;
                } else {
                    children.disable = true;
                }
            }
        }

        // 组装返回包
        JSONObject res = new JSONObject();
        res.put("code", 0);
        //        res.put("msg", "success");
        res.put("data", rootFeatureList);
        return res;
    }


}
